Skip to main content

ngClass

ngClass הוא Attribute directive. זה אומר שהוא שנה את הניראות של אלמנט html שמשתמש בו. ngClass משמש להוספה דינמית של css class לאלמנט html.

בדוגמא ה-class של text-success יופיע ב-div רק במקרה של על true.

component.html
<div [ngClass]="{'text-success': true}">Show Success</div>

דוגמא

נניח שיש לנו alert בעמוד שנעלם כשלוחצים על ה-X. אנחנו רוצים אפקט של fade כשה-alert יעלם.

component.html
<div class="alert alert-success" [hidden]="displayNotification">
This site contain cookies.
<div clas="close"><button class="btn" (click)="closeNotification()">X</button></div>
</div>
component.ts
displayNotification = false;

closeNotification(){
this.displayNotification = true;
}

קודם ניצור את ה-class שמייצר את ה-fade.

component.css
.fadeout{
visibility: hidden;
opacity: 0;
transition: visibility 0s 2s, opacity 2s linear;
}

אנחנו רוצים להחיל את ה-class של fadeout דינמית על ה-alert.

component.html
<div class="alert alert-success" [ngClass]="{ fadeout: displayNotification }">
This site contain cookies.
<div clas="close"><button class="btn" (click)="closeNotification()">X</button></div>
</div>

מערך של ערכים

אפשר להשתמש במערך על classes ולבחור בכל פעם את ה-class שמתאים על פי הערך של משתנה.

component.html
<h4>NgClass</h4>
<ul *ngFor="let person of people">
<li [ngClass]="{
'text-success': person.country === 'UK',
'text-primary': person.country === 'USA',
'text-danger' : person.country === 'HK'
}">{{ person.name }} - {{ person.country }}
</li>
</ul>

הוספה של ערך

אם לא רוצים לשנות את כל ה-classes שיש לאלמנט, אלא להוסיף ערך, נשתמש בתחביר הבא:

component.html
<ul *ngFor="let person of people">
<li [class.text-success]="person.country === 'UK'"
[class.text-primary]="person.country === 'USA'"
[class.text-danger]="person.country === 'HK'">
{{ person.name }} - {{ person.country }}
</li>
</ul>